//== 通知 - 列表页
let SysMessageList = function () {
    /**
     * 初始化列表
     */
    let initTable = function (options) {
        if (SysMessageList.dataTable != null) {
            // 销毁表格
            SysMessageList.dataTable.destroy();
        }
        SysMessageList.dataTable = ETool.initDataTable(options);
    };
    /**
     * 打开页面
     *
     * @param url {string} 访问地址
     */
    let openUrl = function (url) {
        let $ListView = $('#list-view');
        let $inputView = $('#input-view');

        EUtil.ajax({
            url: url,
            wait: '.view-container',
            dataType: 'html',
            success: function (res) {
                $inputView.html(res);
                $ListView.addClass('e-hide');
                $inputView.removeClass('e-hide');
                EApp.animateCSS('#input-view', EApp.getAnimate('in'), null);
                SysMessageInput.init();
            }
        });
    };

    /**
     * 处理链接点击事件
     *
     * @param element
     */
    let processingLinks = function (element) {
        function updateNavActive($element) {
            $element.parents('ul.e-nav').find('.e-nav-item').removeClass('active');
            $element.parent().addClass('active');
        }

        let $element = $(element);
        let type = $element.data('type');
        let $ListView = $('#list-view');
        let $inputView = $('#input-view');
        let $messageTypeUl = $('ul.e-nav.message-type');

        // 更新nav
        updateNavActive($element);
        if ('html' === type) {
            // 隐藏类型筛选
            EApp.animateCSS('ul.e-nav.message-type', EApp.getAnimate('out'), function () {
                $messageTypeUl.addClass('e-hide');
            });
            // 普通链接
            openUrl($element.data('url'));
        } else {
            // 显示类型筛选
            if ($messageTypeUl.hasClass('e-hide') ||
                $messageTypeUl.hasClass(EApp.getAnimate('out'))) {
                // 防止用户点了写信马上点收信导致类型筛选器隐藏,所以同时检查筛选器是否正在隐藏过程中
                $messageTypeUl.removeClass('e-hide');
                EApp.animateCSS('ul.e-nav.message-type', EApp.getAnimate('in'), function () {
                    $messageTypeUl.removeClass('e-hide');
                });
                // 恢复默认类型筛选
                $messageTypeUl.find('.e-nav-item').removeClass('active');
                $messageTypeUl.find('.e-nav-item:eq(0)').addClass('active');
                $('#type').val('');
            }

            // 显示列表
            if ($ListView.hasClass('e-hide')) {
                // 切换到列表视图
                $inputView.addClass('e-hide');
                $ListView.removeClass('e-hide');
                EApp.animateCSS('#list-view', EApp.getAnimate('in'), null);
            }

            // 调用指定callback
            let callback = ETool.getObject($element.data('callback'), window);
            if (EUtil.isFunction(callback)) {
                callback($element);
            }
        }
    };
    /**
     * 绑定导航点击事件
     */
    let bindNavClick = function () {
        $('.e-nav a[data-type], .e-nav a[data-callback]').click(function () {
            processingLinks(this);
        });

        $('body').on('click', '.message-link', function () {
            openUrl($(this).data('url'));
        })
    };
    /**
     * 获取标题区域可用宽度
     * @return {number}
     */
    let getTitleWidth = function () {
        let minWidth = 320;
        let width = EUtil.getViewPort().width - 800;
        return Math.max(minWidth, width);
    };
    /**
     * 初始化收信表格
     * @param $element 触发的按钮
     */
    let initReceive = function ($element) {
        let messageType = $element.data('message-type');
        let $status = $('#status');
        let $star = $('#star');
        let $detailsStatus = $('#detailsStatus');
        // 消息必须是已发送
        $status.val(STATUS_HAS_BEEN_SENT);
        $star.val('');
        $detailsStatus.val('');

        if (INBOX === messageType) {
            // 收信箱
            selectUnreadCount();
            $('.btn-delete, .btn-delete-completely, .btn-all-read').removeClass('e-hide');
        } else if (INSTAR_SIGNBOX === messageType) {
            $('.btn-delete, .btn-delete-completely, .btn-all-read').removeClass('e-hide');
            // 标星
            $star.val(STAR_YES);
        } else if (RECYCLE_BIN === messageType) {
            $('.btn-delete-completely').removeClass('e-hide');
            $('.btn-delete, .btn-all-read').addClass('e-hide');
            // 回收站
            $detailsStatus.val(RECEIVE_STATUS_DELETED);
        }
        let titleWidth = getTitleWidth();
        let columns = [
            {
                field: 'id',
                title: '#',
                sortable: false, // 禁用此列排序
                width: 40,
                selector: {class: 'e-checkbox--solid'}
            }
        ];
        if (RECYCLE_BIN !== messageType) {
            // 如果不是回收站则显示收藏/取消收藏
            columns.push({
                field: 'star',
                title: '标星',
                width: 40,
                template: function (row) {
                    let stared = null;
                    if (STAR_YES === row.star) {
                        stared = 'e-svg-icon-brand';
                    }
                    return '<a href="#" data-id="' + row.id + '" data-star="' + (STAR_YES === row.star) + '" onclick="SysMessageList.setStar(this)" class="star-message">' +
                        '   <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1" class="e-svg-icon ' + (stared ? stared : 'e-svg-icon-invalid') + '">\n' +
                        '     <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n' +
                        '            <polygon id="Shape" points="0 0 24 0 24 24 0 24"/>\n' +
                        '            <path d="M12,18 L7.91561963,20.1472858 C7.42677504,20.4042866 6.82214789,20.2163401 6.56514708,19.7274955 C6.46280801,19.5328351 6.42749334,19.309867 6.46467018,19.0931094 L7.24471742,14.545085 L3.94038429,11.3241562 C3.54490071,10.938655 3.5368084,10.3055417 3.92230962,9.91005817 C4.07581822,9.75257453 4.27696063,9.65008735 4.49459766,9.61846284 L9.06107374,8.95491503 L11.1032639,4.81698575 C11.3476862,4.32173209 11.9473121,4.11839309 12.4425657,4.36281539 C12.6397783,4.46014562 12.7994058,4.61977315 12.8967361,4.81698575 L14.9389263,8.95491503 L19.5054023,9.61846284 C20.0519472,9.69788046 20.4306287,10.2053233 20.351211,10.7518682 C20.3195865,10.9695052 20.2170993,11.1706476 20.0596157,11.3241562 L16.7552826,14.545085 L17.5353298,19.0931094 C17.6286908,19.6374458 17.263103,20.1544017 16.7187666,20.2477627 C16.5020089,20.2849396 16.2790408,20.2496249 16.0843804,20.1472858 L12,18 Z" id="Star" fill="#000000"/>\n' +
                        '      </g>\n' +
                        '    </svg>' +
                        '</a>';
                }
            });
        }
        columns.push({
            field: 'title',
            title: '主题',
            width: titleWidth,
            template: function (row) {
                return '\
                    <div class="e-user-card-hor">\
                        <div class="e-user-card-hor-pic">\
                            ' + (EUtil.isNotBlank(row.avatar) ? '<img src="' + basePath + row.avatar + '" alt="photo">' : '<span class="badge badge--unified-info badge--lg badge--bold">' + row.nickname.substr(0, 1) + '</span>') + '  \
                        </div>\
                        <div class="e-user-card-hor-details">\
                            <a href="#" data-url="' + ETool.getBaseUrl() + 'info/' + row.messageId + '/' + row.id + '" class="e-user-card-hor-name message-link' + (row.readDate ? '' : ' unread') + '">' +
                            (row.important === IMPORTANT_YES ? '<span class="badge badge--danger badge--inline badge--unified-danger">重要</span> ' : '') +
                            row.title + '</a>\
                            <span class="e-user-card-hor-email">' + row.nickname + '</span>\
                        </div>\
                    </div>';
            }
        });

        columns.push({
            field: 'sendDate',
            title: '类型/时间',
            width: 120,
            sortable: 'desc',
            template: function (row) {
                let typeDicts = ETool.getSysDictsObjectByDictType('messageType');
                return '\
                        <div class="e-user-card-hor">\
                            <div class="e-user-card-hor-details">\
                                <a href="#" class="e-user-card-hor-name">' + ETool.getDictElement(row.type, typeDicts) + '</a>\
                                <span class="e-user-card-hor-email" title="' + row.sendDate + '">' + (moment(row.sendDate, 'YYYY-MM-DD HH:mm:ss').fromNow()) + '</span>\
                            </div>\
                        </div>';
            }
        });
        columns.push({
            field: 'Actions',
            width: 110,
            title: '操作',
            sortable: false,
            template: function (row, index, datatable) {
                let _btn = '';
                if (ETool.hasPermissions('sys:message:delete')) {
                    if (RECYCLE_BIN === messageType) {
                        // 回收站
                        _btn += '<a href="#" data-id="' + row.id + '" onclick="SysMessageList.reduction(this)" class="' + ETool.ACTIONS_SUCCESS + '" title="还原">\
                                    <i class="la la-rotate-left"></i>\
                                </a>';
                        _btn += '<a href="#" data-id="' + row.id + '" onclick="SysMessageList.deleteData(this, true)" class="' + ETool.ACTIONS_DANGER + '" title="彻底删除">\
                                    <i class="la la-trash"></i>\
                                </a>';
                    } else {
                        _btn += '<a href="#" data-id="' + row.id + '" onclick="SysMessageList.deleteData(this, false)" class="' + ETool.ACTIONS_DANGER + '" title="移至回收站">\
                                    <i class="la la-trash"></i>\
                                </a>';
                    }
                }
                return _btn;
            }
        });
        // 收信
        initTable({
            url: ETool.getBaseUrl() + 'select/receive',
            columns: columns
        });
    };
    /**
     * 初始化发信表格
     * @param $element 触发的按钮
     */
    let initSend = function ($element) {
        let messageType = $element.data('message-type');
        let $status = $('#status');
        if (DRAFTS === messageType) {
            // 草稿箱
            $status.val(STATUS_DRAFT);
        } else if (HAS_BEEN_SENT === messageType) {
            // 已发送
            $status.val(STATUS_HAS_BEEN_SENT);
        }
        $('.btn-delete, .btn-delete-completely, .btn-all-read').addClass('e-hide');
        let titleWidth = getTitleWidth();
        let columns = [
            {
                field: 'id',
                title: '#',
                sortable: false, // 禁用此列排序
                width: 40,
                selector: {class: 'e-checkbox--solid'}
            },
            {
                field: 'title',
                title: '主题',
                width: titleWidth,
                template: function (row) {
                    return '\
                        <div class="e-user-card-hor">\
                            <div class="e-user-card-hor-pic">\
                                ' + (EUtil.isNotBlank(row.avatar) ? '<img src="' + basePath + row.avatar + '" alt="photo">' : '<span class="badge badge--unified-info badge--lg badge--bold">' + row.nickname.substr(0, 1) + '</span>') + '  \
                            </div>\
                            <div class="e-user-card-hor-details">\
                                <a href="#" class="e-user-card-hor-name">' +
                        (row.important === 1 ? '<span class="badge badge--danger badge--inline badge--unified-danger">重要</span> ' : '') +
                        row.title + '</a>\
                                <span class="e-user-card-hor-email">' + row.nickname + '</span>\
                            </div>\
                        </div>';
                }
            },
            {
                field: 'sendDate',
                title: '类型/时间',
                width: 100,
                template: function (row) {
                    let typeDicts = ETool.getSysDictsObjectByDictType('messageType');
                    return '\
                        <div class="e-user-card-hor">\
                            <div class="e-user-card-hor-details">\
                                <a href="#" class="e-user-card-hor-name">' + ETool.getDictElement(row.type, typeDicts) + '</a>\
                                ' + (row.sendDate ? '<span class="e-user-card-hor-email">' + row.sendDate + '</span>' : '<span class="e-user-card-hor-email">--</span>') + '\
                            </div>\
                        </div>';
                }
            }
        ];
        if ($status.val() !== STATUS_HAS_BEEN_SENT) {
            columns.push({
                field: 'Actions',
                width: 110,
                title: '操作',
                sortable: false,
                template: function (row, index, datatable) {
                    let _btn = '';
                    if (ETool.hasPermissions('sys:message:save')) {
                        _btn += '<a href="#" data-id="' + row.id + '" onclick="SysMessageList.send(this)" class="' + ETool.ACTIONS_INFO + '" title="发送">\
                                <i class="la la-send"></i>\
                            </a>';
                    }
                    if (ETool.hasPermissions('sys:message:save')) {
                        _btn += '<a href="#" data-url="'+ETool.getBaseUrl() + 'input/' + row.id +'" class="message-link ' + ETool.ACTIONS_INFO + '" title="编辑">\
                                <i class="la la-edit"></i>\
                            </a>';
                    }
                    if (ETool.hasPermissions('sys:message:delete')) {
                        _btn += '<a href="#" onclick="ETool.deleteById(this, \'' + row.id + '\')" class="' + ETool.ACTIONS_DANGER + '" title="删除">\
                                <i class="la la-trash"></i>\
                            </a>';
                    }
                    return _btn;
                }
            });
        }
        // 刷新表格数据
        initTable({
            url: ETool.getBaseUrl() + 'select',
            columns: columns
        });
    };
    /**
     * 根据类型过滤信息
     *
     * @param $element 触发的按钮
     */
    let filterByType = function ($element) {
        $('#type').val($element.data('data-type'));
        // 重新加载数据
        SysMessageList.dataTable.reload();
    };
    /**
     * 设置标星/取消标星
     *
     * @param element {object} 触发按钮
     */
    let setStar = function (element) {
        let $element = $(element);
        EUtil.ajax({
            url: ETool.getBaseUrl() + 'details/set/star/' + $element.data('id') + '/' + !$element.data('star'),
            success: function (res) {
                ETool.successTip(commonTips.success, $element.data('star') ? '已取消收藏' : '已收藏');
                SysMessageList.dataTable.reload();
            }
        });
    };
    /**
     * 删除按钮对应的tooltip
     *
     * @param element 按钮
     */
    let hideBtnTip = function (element) {
        let tooltipId = $(element).attr('aria-describedby');
        if(EUtil.isNotBlank(tooltipId)){
            $('#' + tooltipId).remove();
        }
    };
    /**
     * 移至回收站/彻底删除
     *
     * @param element {object} 触发按钮
     * @param deleteCompletely {boolean} true/false 是否彻底删除
     */
    let deleteData = function (element, deleteCompletely) {
        let id = null;
        if (element) {
            // 传入了按钮对象
            id = $(element).data('id');
        }
        if (EUtil.isBlank(id)) {
            // 获取表格中的选中项
            id = SysMessageList.dataTable.getValue().join(',');
        }
        if (EUtil.isBlank(id)) {
            ETool.warnTip(commonTips.fail, '请在表格中选中要删除的数据后重试');
            return;
        }
        let _delete = function () {
            EUtil.ajax({
                url: ETool.getBaseUrl() + 'details/delete/' + id + '/' + deleteCompletely,
                success: function (res) {
                    ETool.successTip(commonTips.success, deleteCompletely ? '消息已彻底删除' : '消息已移至回收站');
                    SysMessageList.dataTable.reload();
                }
            });
        };
        if (deleteCompletely) {
            EUtil.alertConfirm('彻底删除', '彻底删除后无法还原，确定要删除吗？', function () {
                _delete(element);
            });
        } else {
            hideBtnTip(element);
            _delete(element);
        }
    };

    /**
     * 从回收站还原消息
     *
     * @param element {object} 触发按钮
     */
    let reduction = function (element) {
        let $element = $(element);
        hideBtnTip(element);
        EUtil.ajax({
            url: ETool.getBaseUrl() + 'details/reduction/' + $element.data('id'),
            success: function (res) {
                ETool.successTip(commonTips.success, '消息已还原');
                SysMessageList.dataTable.reload();
            }
        });
    };

    /**
     * 设置消息已读
     */
    let setRead = function () {
        let _setRead = function (ids) {
            EUtil.ajax({
                url: ETool.getBaseUrl() + 'details/set/read',
                data: {
                    ids: ids
                },
                success: function (res) {
                    ETool.successTip(commonTips.success, '消息已设置为已读');
                    SysMessageList.dataTable.reload();
                }
            });
        };
        let ids = SysMessageList.dataTable.getValue();
        let idStr = ids.join(',');
        // 如果未勾选数据,表示全部标记已读
        let subtitle;
        if (EUtil.isBlank(idStr)) {
            subtitle = '确定要将所有消息设置为已读吗？'
        } else {
            subtitle = '确定要将选择的' + ids.length + '条消息设置为已读吗？';
        }
        EUtil.alertConfirm('标记已读', subtitle, function () {
            _setRead(idStr);
        })
    };

    /**
     * 发送
     *
     * @param element {object} 触发按钮
     */
    let send = function (element) {
        EUtil.alertConfirm('发送消息', '发送后无法撤销，确定要发送吗？', function () {
            hideBtnTip(element);
            let $element = $(element);
            EUtil.ajax({
                url: ETool.getBaseUrl() + 'send/' + $element.data('id'),
                success: function (res) {
                    ETool.successTip(commonTips.success, '消息已发送');
                    SysMessageList.dataTable.reload();
                }
            });
        })
    };

    /**
     * 获取当前登录用户查询未读消息数量
     */
    let selectUnreadCount = function(){
        EUtil.ajax({
            url: ETool.getBaseUrl() + 'select/unread/count',
            success: function (res) {
                if (res.data > 0) {
                    $('.unread-count').removeClass('e-hide').html(res.data);
                } else {
                    $('.unread-count').addClass('e-hide').html(res.data);
                }
            }
        });
    };

    return {
        //== 初始化页面
        init: function () {
            ETool.setBaseUrl(basePath + '/auth/sys/message/');
            bindNavClick();
            // 加载默认菜单
            $('.e-nav.data-type .e-nav-item.active > a').click();
            selectUnreadCount();
        },
        /**
         * 初始化收信表格
         * @param $element 触发的按钮
         */
        initReceive: function ($element) {
            initReceive($element);
        },
        /**
         * 初始化发信表格
         * @param $element 触发的按钮
         */
        initSend: function ($element) {
            initSend($element);
        },
        /**
         * 根据类型过滤信息
         *
         * @param $element 触发的按钮
         */
        filterByType: function ($element) {
            filterByType($element);
        },
        /**
         * 设置标星/取消标星
         *
         * @param element {object} 触发按钮
         */
        setStar: function (element) {
            setStar(element);
        },
        /**
         * 移至回收站/彻底删除
         *
         * @param element {object} 触发按钮
         * @param deleteCompletely {boolean} true/false 是否彻底删除
         */
        deleteData: function (element, deleteCompletely) {
            deleteData(element, deleteCompletely);
        },
        /**
         * 从回收站还原消息
         *
         * @param element {object} 触发按钮
         */
        reduction: function (element) {
            reduction(element);
        },
        /**
         * 发送
         *
         * @param element {object} 触发按钮
         */
        send: function (element) {
            send(element);
        },
        /**
         * 设置消息已读
         */
        setRead: function () {
            setRead();
        }
    };
}();
/**
 * 当前tab激活时是否需要重新加载数据
 *
 * @return {boolean} true/false
 */
ETab.needSubmitForm = function () {
    return true;
};
//== 初始化
$(document).ready(function () {
    window.SysMessageList = SysMessageList;
    SysMessageList.init();
});